package com.fxp.project.jiuselu.web.file.domain;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 身法证验证
 */
public class Base64Util {

    private static String strNetImageToBase64;



    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath
     */
    private static String NetImageToBase64(String netImagePath) {
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

//            new Thread(new Runnable() {
//                @Override
//                public void run() {
                    try {
                        InputStream is = conn.getInputStream();
                        // 将内容读取内存中
                        int len = -1;
                        while ((len = is.read(by)) != -1) {
                            data.write(by, 0, len);
                        }
                        // 对字节数组Base64编码
                        BASE64Encoder encoder = new BASE64Encoder();
                        strNetImageToBase64 = encoder.encode(data.toByteArray());
//                        System.out.println("网络图片转换Base64:" + strNetImageToBase64);
                        // 关闭流
                        is.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                }
//            }).start();
            return strNetImageToBase64;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath
     */

    private static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
        return encoder.encode(Objects.requireNonNull(data));
    }


    public static void main(String[] args) {
        //第一个:把网络图片装换成Base64
        String netImagePath = "https://mhzhcg.oss-cn-hangzhou.aliyuncs.com/2022/04/22/49fdd32cc8d9f1fa39f817b7ec7c151_1650594869817.jpg";
        //下面是网络图片转换Base64的方法
//        System.err.println(NetImageToBase64(netImagePath));

        aaa(false,netImagePath);

//        //下面是本地图片转换Base64的方法
//        String imagePath = "本地图片路径";
//        ImageToBase64(imagePath);
    }

    /**
     *
     * @param type true：图像内容为BASE64编码；false：图像内容为图像文件URL链接
     * @param fileParam 文件参数
     */
    public static void aaa(boolean type,String fileParam){
        //API产品路径
        String requestUrl = "https://personcard.market.alicloudapi.com/ai_market/ai_ocr_universal/shen_fen_zheng/ch/v1";
        //阿里云APPCODE
        String appcode = "c769899a65af46e79847bd92e9cb2196";

        CloseableHttpClient httpClient = null;
        try{
            httpClient = HttpClients.createDefault();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // 装填参数
            if (type) {
                //启用BASE64编码方式进行识别
                //内容数据类型是BASE64编码
                String imgBase64 = "";
                try {
                    File file = new File(fileParam);
                    byte[] content = new byte[(int) file.length()];
                    FileInputStream finputstream = new FileInputStream(file);
                    finputstream.read(content);
                    finputstream.close();
                    imgBase64 = new String(ImageToBase64(content.toString()));
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
                params.add(new BasicNameValuePair("IMAGE", imgBase64));
                params.add(new BasicNameValuePair("IMAGE_TYPE", "0"));
            } else {
                //启用URL方式进行识别
                //内容数据类型是图像文件URL链接
                params.add(new BasicNameValuePair("IMAGE", fileParam));
                params.add(new BasicNameValuePair("IMAGE_TYPE", "1"));
            }

            // 创建一个HttpPost实例
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.addHeader("Authorization","APPCODE " + appcode);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 设置请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            // 发送POST请求
            HttpResponse execute = httpClient.execute(httpPost);

            // 获取状态码
            int statusCode = execute.getStatusLine().getStatusCode();
            System.err.println(statusCode);

            // 获取结果
            HttpEntity entity = execute.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            System.err.println(result);
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
